import uuid
from datetime import datetime
from typing import Optional, Dict
from app.utils.db_utils import MySQLHelper
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class UserModel:
    """
    用户模型
    用于管理应用用户信息，包含Shopify店铺相关数据
    """
    
    def __init__(self, auto_commit=False):
        """
        初始化用户模型
        """
        self.db_helper = MySQLHelper(auto_commit=auto_commit)
        self._ensure_table_exists()
    
    def _ensure_table_exists(self):
        """
        确保用户表存在
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute("""
                CREATE TABLE IF NOT EXISTS users (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    user_id VARCHAR(36) NOT NULL,
                    shopify_domain VARCHAR(255) NOT NULL,
                    shop_name VARCHAR(255),
                    shop_owner VARCHAR(255),
                    email VARCHAR(255),
                    country VARCHAR(100),
                    currency VARCHAR(10),
                    plan_name VARCHAR(100),
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    UNIQUE INDEX idx_shopify_domain (shopify_domain),
                    INDEX idx_user_id (user_id),
                    INDEX idx_created_at (created_at)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                """)
            conn.commit()
        except Exception as e:
            logging.error(f"创建用户表失败: {e}")
            if conn:
                conn.rollback()
            raise
    
    def create_user(self, shopify_domain: str, shop_info: Optional[Dict] = None) -> str:
        """
        创建用户记录
        
        Args:
            shopify_domain: Shopify店铺域名
            shop_info: 店铺信息字典（可选）
            
        Returns:
            str: 用户ID
        """
        try:
            user_id = str(uuid.uuid4())
            shop_info = shop_info or {}
            
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute("""
                INSERT INTO users 
                (user_id, shopify_domain, shop_name, shop_owner, email, country, currency, plan_name)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                """,
                (user_id, shopify_domain, 
                 shop_info.get('shop_name'), 
                 shop_info.get('shop_owner'),
                 shop_info.get('email'),
                 shop_info.get('country'),
                 shop_info.get('currency'),
                 shop_info.get('plan_name')))
            conn.commit()
            logging.info(f"成功创建用户: {shopify_domain}, 用户ID: {user_id}")
            return user_id
        except Exception as e:
            logging.error(f"创建用户失败: {e}")
            if conn:
                conn.rollback()
            raise
    
    def get_user_by_domain(self, shopify_domain: str) -> Optional[Dict]:
        """
        根据Shopify域名获取用户信息
        
        Args:
            shopify_domain: Shopify店铺域名
            
        Returns:
            Dict: 用户信息，不存在返回None
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                # 尝试使用shop_domain列名，因为数据库可能使用这个列名
                cursor.execute("""
                SELECT * FROM users WHERE shop_domain = %s
                """, (shopify_domain,))
                result = cursor.fetchone()
                return result
        except Exception as e:
            logging.error(f"获取用户信息失败: {e}")
            raise
    
    def update_user(self, shopify_domain: str, shop_info: Dict) -> bool:
        """
        更新用户信息
        
        Args:
            shopify_domain: Shopify店铺域名
            shop_info: 要更新的店铺信息
            
        Returns:
            bool: 更新是否成功
        """
        try:
            # 构建更新字段
            update_fields = []
            params = []
            
            for field, value in shop_info.items():
                if field in ['shop_name', 'shop_owner', 'email', 'country', 'currency', 'plan_name']:
                    update_fields.append(f"`{field}` = %s")
                    params.append(value)
            
            if not update_fields:
                return True  # 没有需要更新的字段
            
            params.append(shopify_domain)
            
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                query = f"""
                UPDATE users 
                SET {', '.join(update_fields)}
                WHERE shop_domain = %s
                """
                affected_rows = cursor.execute(query, params)
            conn.commit()
            
            logging.info(f"更新用户信息: {shopify_domain}, 影响行数: {affected_rows}")
            return affected_rows > 0
        except Exception as e:
            logging.error(f"更新用户信息失败: {e}")
            if conn:
                conn.rollback()
            raise
    
    def user_exists(self, shopify_domain: str) -> bool:
        """
        检查用户是否存在
        
        Args:
            shopify_domain: Shopify店铺域名
            
        Returns:
            bool: 用户是否存在
        """
        try:
            conn = self.db_helper._get_connection()
            with conn.cursor() as cursor:
                cursor.execute("""
                SELECT COUNT(*) as count FROM users WHERE shop_domain = %s
                """, (shopify_domain,))
                result = cursor.fetchone()
                return result.get('count', 0) > 0
        except Exception as e:
            logging.error(f"检查用户是否存在失败: {e}")
            raise


# 创建用户模型实例
user_model = UserModel()